import React, { useEffect, useState } from 'react'
import { Button, Table, Tag, notification } from 'antd'
import axios from 'axios'

export default function AuditList(props) {
  const [dataSource, setdataSource] = useState([])
  const { username } = JSON.parse(localStorage.getItem("token"))

  const auditList = ["未审核", "审核中", "已通过", "未通过"]
  const colorList = ["black", "orange", "green", "red"]
  const btnList = ["", "撤销", "发布", "更新"]

  useEffect(() => {
    axios.get(`/news?author=${username}&auditState_ne=0&publishState_lte=1&_expand=category`).then(res => {
      setdataSource(res.data)
    })
  }, [username])

  const handleAudit = (item) => {
    if (item.auditState === 1) {
      axios.patch(`/news/${item.id}`, { auditState: 0 }).then(res => {
        setdataSource(dataSource.filter(data => data.id !== item.id))
        notification.info({
          message: `通知`,
          description: `您可以到草稿箱中查看撤回的新闻!`,
          placement: "bottomRight"
        })
      })
    } else if (item.auditState == 2) {
      axios.patch(`/news/${item.id}`, { publishState: 2, publishTime: Date.now() }).then(res => {
        setdataSource(dataSource.filter(data => data.id !== item.id))
        notification.info({
          message: `通知`,
          description: `您可以到【发布管理/已发布】中查看发布的新闻!`,
          placement: "bottomRight"
        })
        // props.history.push(`/publish-manage/published`)
      })
    } else {
      props.history.push(`/news-manage/update/${item.id}`)
    }

  };

  const columns = [
    {
      title: '新闻标题',
      dataIndex: 'title',
      render: (title, item) => {
        return <a href={`#/news-manage/preview/${item.id}`} >{title}</a>
      }
    },
    {
      title: '作者',
      dataIndex: 'author',
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      render: (category) => {
        return category.title
      }
    },
    {
      title: '审核状态',
      dataIndex: 'auditState',
      render: (auditState) => {
        return <Tag color={colorList[auditState]}>{auditList[auditState]}</Tag>
      }
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Button shape="primary" onClick={() => { handleAudit(item) }}>{btnList[item.auditState]}</Button>
        </div>
      }

    },
  ];

  return (
    <div>
      <Table dataSource={dataSource} columns={columns}
        pagination={{
          pageSize: 5
        }}
        rowKey={(item) => item.id}
      />
    </div>
  )
}
